<?php
declare(strict_types=1);

namespace app\common\lib\sms;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\facade\Log;

class AliSms implements SmsBase
{
    /**
     * @param  string  $phone
     * @param  int  $code
     * @return bool
     */
    public static function sendCode(string $phone, int $code): bool
    {
        if(empty($phone) || empty($code)){
            return false;
        }
        $arr = [
            "phoneNumbers" => $phone,
            "signName" => \config('aliyun.sign_name'),
            "templateCode" => \config('aliyun.template_code'),
            "templateParam" => "{code:$code}"
        ];
        $ret = self::main([], $arr);
        return $ret;
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param  string  $accessKeyId
     * @param  string  $accessKeySecret
     * @return Dysmsapi Client
     */
    protected static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = \config('aliyun.host');
        return new Dysmsapi($config);
    }

    /**
     * @param  string[]  $args
     * @return bool
     */
    protected static function main($args, $data)
    {
        $client = self::createClient(\config('aliyun.accessKeyId'), \config("aliyun.accessKeySecret"));
        $sendSmsRequest = new SendSmsRequest($data);
        // 复制代码运行请自行打印 API 的返回值
        $ret =  $client->sendSms($sendSmsRequest);
        if (($ret->body->code != "OK")) {
            Log::write(json_encode($ret->body));
            return false;
        }
        return true;
    }
}